package com.gcsoftware.web.test.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.toolkit.StringUtils;
import com.gcsoftware.web.test.entity.UserInfo;
import com.gcsoftware.web.test.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.*;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by qs on 2018/4/16.
 */
@Service("userService")
@CacheConfig(cacheNames = "userCache")
public class UserService {
    @Autowired
    private UserMapper userMapper;

    @Cacheable(value = "list")
    public List<UserInfo> findList(String userName) {
        UserInfo info = null;
        Wrapper<UserInfo> wrapper = null;
        if (StringUtils.isNotEmpty(userName)) {
            info = new UserInfo();
            info.setUserName(userName);
            wrapper = new EntityWrapper<>(info);
        }
        return userMapper.selectList(wrapper);
    }

    @Cacheable
    public UserInfo get(String id, String loginName, String userEmail) {
        UserInfo userInfo = new UserInfo() ;
        userInfo.setId(id);
        userInfo.setUserEmail(userEmail);
        userInfo.setLoginName(loginName);
        return userMapper.selectOne(userInfo);
    }

    @Caching(
            evict = @CacheEvict(value = "list", allEntries = true),
            put = @CachePut(key = "#userInfo.id")
    )
    public UserInfo insert(UserInfo userInfo) {
        userMapper.insert(userInfo);
        return userInfo;
    }

    @Caching(
            evict = {@CacheEvict(value = "list", allEntries = true), @CacheEvict(key = "#userId")}
    )
    public int delete(String userId) {
        return userMapper.deleteById(userId);
    }

    @Caching(
            evict = @CacheEvict(value = "'list'"),
            put = @CachePut(key = "#userInfo.id")
    )
    public int update(UserInfo userInfo) {
        return userMapper.updateById(userInfo);
    }

}
